package cn.exrick.controller;


import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import cn.exrick.pojo.TbItemCat;
import cn.exrick.pojo.common.Result;
import cn.exrick.pojo.common.ZTreeNode;
import cn.exrick.service.ItemCatService;
import cn.exrick.utils.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * Created by Exrick on 2017/8/2.
 */
@RestController
@Api(description = "商品分类信息")
public class ItemCatController {

    @Autowired
    private ItemCatService itemCatService;
    
    @RequestMapping(value = "/item/cat/list4back", method = RequestMethod.GET)
    @ApiOperation(value = "通过父ID获取商品分类列表")
    public Result<List<ZTreeNode>> getItemCatList4Back(@RequestParam(name = "id", defaultValue = "0") int parentId) {

        List<ZTreeNode> list = itemCatService.getItemCatList(parentId,-1);
        if (list != null && list.size() > 0 && list.get(0).getId() == -1) {
            list.remove(0);
        }
        return new ResultUtil<List<ZTreeNode>>().setData(list);
    }

    @RequestMapping(value = "/item/cat/list", method = RequestMethod.GET)
    @ApiOperation(value = "通过父ID获取商品分类列表")
    public Result<List<ZTreeNode>> getItemCatList(@RequestParam(name = "id", defaultValue = "0") int parentId) {

        List<ZTreeNode> list = itemCatService.getItemCatList(parentId,1);
        if (list != null && list.size() > 0 && list.get(0).getId() == -1) {
            list.remove(0);
        }
        return new ResultUtil<List<ZTreeNode>>().setData(list);
    }

    @RequestMapping(value = "/item/cat/add", method = RequestMethod.POST)
    @ApiOperation(value = "添加商品分类")
    public Result<Object> addItemCategory(@ModelAttribute TbItemCat tbItemCat) {
        if(tbItemCat.getParentId() == -1){
            tbItemCat.setParentId(0L);
        }
        itemCatService.addItemCat(tbItemCat);
        return new ResultUtil<Object>().setData(null);
    }

    @RequestMapping(value = "/item/cat/update", method = RequestMethod.POST)
    @ApiOperation(value = "编辑商品分类")
    public Result<Object> updateItemCategory(@ModelAttribute TbItemCat tbItemCat) {
        itemCatService.updateItemCat(tbItemCat);
        return new ResultUtil<Object>().setData(null);
    }

    @RequestMapping(value = "/item/cat/del/{id}", method = RequestMethod.DELETE)
    @ApiOperation(value = "删除商品分类")
    public Result<Object> deleteItemCategory(@PathVariable Long id) {

        itemCatService.deleteItemCat(id);
        return new ResultUtil<Object>().setData(null);
    }
}
